package com.banmao.CarlCamp.Day02;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

/**
 *  https://leetcode.cn/problems/spiral-matrix-ii/
 */
@Slf4j
public class LC59 {

    public int[][] generateMatrix(int n) {
        // 螺旋矩阵需要处理好边界问题
        // 确定每一条边左闭右开，上闭下开
        int[][] nums = new int[n][n];
        int x = 0, y = 0;
        int type = 1; // 1-上，2-右，3-下，0-左
        int offset = 0;
        for (int i = 1; i <= n * n; i++) {
            if (x == n || y == n) {
                break;
            }
            switch (type % 4) {
                case 1:
                    nums[x][y] = i;
                    if (y++ == n - offset - 2) {
                        type++;
                    }
                    break;
                case 2:
                    nums[x][y] = i;
                    if (x++ == n - offset - 2) {
                        type++;
                    }
                    break;
                case 3:
                    nums[x][y] = i;
                    if (y-- == offset + 1) {
                        type++;
                    }
                    break;
                case 0:
                    nums[x][y] = i;
                    if (x-- == offset + 1) {
                        type++;
                        offset++;
                        x += 1;
                        y += 1;
                    }
                    break;
            }
        }
        return nums;
    }

    public static void main(String[] args) {
        LC59 lc59 = new LC59();
        int[][] ints = lc59.generateMatrix(5);
        log.info("{}", JSON.toJSONString(ints));
    }

}
